#!/usr/bin/perl -w

# This File is only an example to move converted Files
# to a online drive or something others spaces
# 
# A special modus is 'remove' as first parameter, to delete 
# mp4 Files on remote Server.
# 
# You can call:
# 
# xipodcast.post 1.mp4 2.mp4 ... to move mp4 files to server
# 
# or
# 
# xipodcast.post remove 1.mp4 2.mp4 ... to remove mp4 files on remote server

use warnings;
use strict;

use File::Basename;
use Data::Dumper;

# This is my personal settings! ;)
my $MP4FILE = shift || die "No MP4 File!";
my @mp4files_to_remove = @ARGV;
my $TARGETDIR = "/var/www/webdav/xipodcast";
my $SSHIDENT = "root\@xpix.dieserver.de";
# This is my personal settings! ;)


if($MP4FILE eq 'remove'){
   # Remove!!! -----
   die 'No Files to remove!!!' unless(scalar @mp4files_to_remove);
   map { $_ = $TARGETDIR . '/' . basename($_) } @mp4files_to_remove;
   my $mp4files_to_remove_as_string = join(" ", @mp4files_to_remove);
   my $erg = `ssh $SSHIDENT 'rm $mp4files_to_remove_as_string'`;
   print $erg;

} elsif($MP4FILE eq 'size'){
   # Size -----
   die 'No Files to size!!!' unless(scalar @mp4files_to_remove);
   my $TARGETMP4 = $TARGETDIR . '/' . basename(shift @mp4files_to_remove);
   my $target_size = (split(/\s/, `ssh $SSHIDENT 'du -b $TARGETMP4 2> /dev/null'`))[0] || 0;
   print $target_size."\n";

} else {
   # Move!!! -----

   my $TARGETMP4 = $TARGETDIR . '/' . basename($MP4FILE);
   my $target_size = (split(/\s/, `ssh $SSHIDENT 'du -b $TARGETMP4 2> /dev/null'`))[0] || 0;
   printf "SrcSize: %s <=> TargetSize: %s\n", -s $MP4FILE, $target_size;
   
   if($target_size != -s $MP4FILE and -s $MP4FILE > 1024){
     my $erg = system('scp', $MP4FILE, sprintf('%s:%s', $SSHIDENT, $TARGETMP4));	
     printf "SSHResult: %s\n", $erg;
     unless($erg){
       # Delete copied mp4 file and create a textfile with copy info
       # also for xipodcast to signal this file is converted
       my $erg = `echo "converted and copied to $SSHIDENT $TARGETMP4" > $MP4FILE`;
     }
   }

}


exit;
